package com.atech.ace.web;

import java.io.IOException;

import javax.ejb.EJB;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.atech.ace.business.client.UserAdministrationRemote;
import com.atech.ace.dao.UserHome;
import com.atech.ace.entity.User;

/**
 * Servlet implementation class UserController
 */
public class UserController extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private String LOGIN = "/auth";
	private String REGISTER = "/register";
	@EJB
	private UserAdministrationRemote admin;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UserController() {
        super();
        // TODO Auto-generated constructor stub
    }
    
    

	@Override
	public void init(ServletConfig config) throws ServletException {
		// TODO Auto-generated method stub
		super.init(config);
		
	}



	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String action = request.getServletPath();
		String nextPage = "";
		
		if(action.equals(LOGIN))
		{
			
			User user = new User();
			user.setUserName(request.getParameter("username"));
			user.setPassword(request.getParameter("password"));
			user = admin.authenticate(user);
			if(user != null && user.getUserId() != null)
			{
				request.getSession().setAttribute("user", user);
				nextPage = "/catalog";
				
			}
			else
			{
				request.setAttribute("err","true");
				nextPage = "/login.jsp";
			}
		}
		else if(action.equals(REGISTER))
		{
			User user = new User();
			user.setUserName(request.getParameter("uname"));
			user.setPassword(request.getParameter("pwd"));
			user.setFirstName(request.getParameter("fname"));
			user.setLastName(request.getParameter("lname"));
			user.setEMail(request.getParameter("email"));
			user.setAddress(request.getParameter("address"));
			user.setIsAdmin(false);
			System.out.println(user);
			
			admin.registerUser(user);
			nextPage = "/login.jsp";
			
		}
		
		getServletConfig().getServletContext().getRequestDispatcher(nextPage).forward(request,response);
	}

}
